package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.resultpage.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.omg.CORBA.portable.UnknownException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    // 登录
    public JsonResult login(String username, String password, HttpSession session){
        try {
            // 获取主体对象
            Subject subject = SecurityUtils.getSubject();
            // 使用主体进行登录
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            subject.login(token);
            return new JsonResult();
        }catch (UnknownAccountException e) {
            return new JsonResult(false, "账号不存在");
        }catch (IncorrectCredentialsException e) {
            return new JsonResult(false, "密码错误");
        }catch (Exception e){
            // 控制台会抛出异常
            e.printStackTrace();
            // 返回错误的提示信息给用户
            return new JsonResult(false,"登陆失败");
        }
    }

   /* // 注销
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();// 销毁会话
        return "redirect:/login.html";
    }*/
}

 /*try {
         Employee employee = employeeService.login(username, password);
         if(!employee.isAdmin()){
         List<String> permissions = permissionService.selectByEmpId(employee.getId());
        session.setAttribute("EXPRESSION_IN_SESSION",permissions);
        }
        // 把当前登录员工的用户密码放到session作用域中
        session.setAttribute("USER_IN_SESSION",employee);
        // 如果不是管理员,就需要查询权限信息

        return new JsonResult();
        }catch (Exception e){
        // 控制台会抛出异常
        e.printStackTrace();
        // 返回错误的提示信息给用户
        return new JsonResult(false,e.getMessage());
        }
        }

// 注销
@RequestMapping("/logout")
public String logout(HttpSession session){
        session.invalidate();// 销毁会话
        return "redirect:/login.html";
        }*/
